<template>
    <Tabs v-model="activeTab" @on-click="handleTabChange">
        <TabPane label="当前借阅" name="current">
            <Table :columns="currentColumns" :data="currentRecords" />
            <!-- 分页组件可以根据需要启用 -->
            <!-- <Page :total="currentTotal" :current="currentPage" :page-size="pageSize"
                @on-change="(page) => handlePageChange(page, 'current')" /> -->
        </TabPane>

        <TabPane label="借阅记录" name="history">
            <Table :columns="historyColumns" :data="historyRecords" />
            <Button type="error" @click="handleDeleteAll">一键删除所有记录</Button>
            <!-- 分页组件可以根据需要启用 -->
            <!-- <Page :total="historyTotal" :current="historyPage" :page-size="pageSize"
                @on-change="(page) => handlePageChange(page, 'history')" /> -->
        </TabPane>
    </Tabs>
</template>

<script>
import { ref, onMounted } from "vue";
import { getCurrentUserRecord, getCurrentUserUnReturnRecord, deleteRecordByUsername, returnBook } from "../api/record.js";
import { Tabs, TabPane, Table, Button, Message } from "view-ui-plus";

export default {
    components: { Tabs, TabPane, Table, Button },
    setup() {
        const activeTab = ref("current");  // 当前激活的Tab
        const currentRecords = ref([]);    // 当前借阅记录
        const historyRecords = ref([]);    // 历史借阅记录
        const currentPage = ref(1);        // 当前借阅记录的页码
        const historyPage = ref(1);        // 历史借阅记录的页码
        const currentTotal = ref(0);       // 当前借阅记录的总数
        const historyTotal = ref(0);       // 历史借阅记录的总数
        const pageSize = ref(10);          // 每页显示的记录数量

        // 获取 Cookie 中的 token
        function getCookieToken() {
            const name = "token=";
            const decodedCookie = decodeURIComponent(document.cookie);
            const ca = decodedCookie.split(";");
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i].trim();
                if (c.indexOf(name) === 0) {
                    return c.substring(name.length, c.length);
                }
            }
        }

        const token = getCookieToken(); // 获取 token

        // 当前借阅表格列配置
        const currentColumns = [
            { title: "书名", key: "bookName" },
            { title: "作者", key: "bookAuthor" },
            { title: "出版社", key: "bookPress" },
            { title: "借阅时间", key: "bookBorrowtime" },
            {
                title: "操作",
                key: "actions",
                render: (h, { row }) => {
                    return h(Button, {
                        type: "primary",
                        size: "small",
                        onClick: () => handleReturn(row.bookId),
                    }, { default: () => "归还" });
                },
            },
        ];

        // 历史借阅表格列配置
        const historyColumns = [
            { title: "书名", key: "recordBookname" },
            { title: "ISBN", key: "recordBookisbn" },
            { title: "借阅者", key: "recordBorrower" },
            { title: "借阅时间", key: "recordBorrowtime" },
            { title: "归还时间", key: "recordRemandtime" },
        ];

        // 获取借阅记录
        const fetchRecords = async () => {
            const isCurrentTab = activeTab.value === 'current';

            try {
                const response = isCurrentTab
                    ? await getCurrentUserUnReturnRecord(token)
                    : await getCurrentUserRecord(token);

                // 根据 request.js 的拦截器，response 已经是 response.data
                if (response && response.success) {
                    const { data } = response;
                    if (isCurrentTab) {
                        currentRecords.value = data;  // 未归还书籍列表
                        currentTotal.value = data.length;
                    } else {
                        historyRecords.value = data;  // 历史借阅记录
                        historyTotal.value = data.length;
                    }
                } else {
                    Message.error(response.message || "获取记录失败");
                }
            } catch (error) {
                console.error("获取记录时出错:", error);
                Message.error("获取记录失败，请稍后重试");
            }
        };

        // 切换 Tab 时更新数据
        const handleTabChange = (name) => {
            activeTab.value = name;
            fetchRecords(); // 切换标签页时更新数据
        };

        // 处理归还操作
        const handleReturn = async (bookId) => {
            console.log("尝试归还ID为的书籍:", bookId);
            try {
                const response = await returnBook(bookId, token);
                if (response && response.success) {
                    Message.success("图书归还成功");
                    await fetchRecords();
                } else {
                    Message.error(response?.message || "归还图书失败，请稍后重试");
                }
            } catch (error) {
                console.error("归还书籍时出错:", error);
                Message.error("归还图书失败，请稍后重试");
            }
        };

        // 一键删除所有历史借阅记录
        const handleDeleteAll = async () => {
            // Check if there are any records that have not been returned
            const hasUnreturnedBooks = historyRecords.value.some(record => !record.recordRemandtime);

            if (hasUnreturnedBooks) {
                Message.warning("还有图书正在借阅中，无法删除记录");
                return;
            }

            if (historyRecords.value.length === 0) {
                Message.warning("没有记录可删除");
                return;
            }

            try {
                // Delete each history record
                for (const record of historyRecords.value) {
                    await deleteRecordByUsername(record.recordBorrower, token, record.recordBookisbn);
                }
                Message.success("所有记录已删除");
                historyRecords.value = []; // Clear the records after deletion
                await fetchRecords();  // 刷新记录
            } catch (error) {
                console.error("删除记录时出错:", error);
                Message.error("删除记录失败，请稍后重试");
            }
        };

        onMounted(() => {
            fetchRecords();  // 组件挂载时获取记录
        });

        return {
            activeTab,
            currentRecords,
            historyRecords,
            currentColumns,
            historyColumns,
            currentPage,
            historyPage,
            currentTotal,
            historyTotal,
            pageSize,
            fetchRecords,
            handleTabChange,
            handleReturn, // 暴露归还方法
            handleDeleteAll, // 暴露一键删除方法
        };
    },
};
</script>

<style scoped>
/* 样式可根据需要自定义 */
</style>